import router, { Cookies, nowToken } from '@/router'
import { useChatStore, useFriendStore } from '@/stores'
import { getFriendsService, getVerifyMsgService } from '@/api/chat.js'
import { h } from 'vue'
const WS = "ws://127.0.0.1:3000"
    // const WS = "https://ws.lvfeiy.com"
export let ws;
const chatStore = useChatStore();
const friendStore = useFriendStore();
export const init = () => {
    ws = new WebSocket("ws://127.0.0.1:3000");
    ws.onmessage = message;
    ws.onclose = (e) => {
        console.log(e);
        ws.close();
    }
    new Promise((r, c) => {
        ws.onopen = (() => {
            r();
        })
    }).then(() => {
        send(login);
    })

}
let login = {
    type: "1",
    data: {
        "token": nowToken
    }
}
export const send = (msg) => {
    ws.send(JSON.stringify(msg))
}
const message = async(e) => {
    if (e) {
        const resp = JSON.parse(e.data);
        console.log('收到ws', resp.type)
        switch (resp.type) {
            case '200':
                ElMessage.success('连接成功');
                break;
            case '-1':
                ElMessage.error('网络不佳，请重新登录');
                router.push('/')
                break;
            case '3':
                const { data: verifyRes } = await getVerifyMsgService();
                console.log(verifyRes)
                chatStore.setVerifyMsg(verifyRes.data);
                ElNotification({
                    title: '收到的好友请求',
                    message: h('i', { style: 'color: teal' }, '请前往好友页进行确认'),
                    duration: 0,
                })
                break;
            case '2':
                chatStore.receiveMsg(resp.data);
                break;
            case '4':
                const { data: flushresp } = await getFriendsService();
                friendStore.setFriend(flushresp.data);
                break;
            case '5':
                const { data: res } = await getFriendsService();
                friendStore.setFriend(res.data);
                chatStore.addHelloMsg(resp.data)
                break;
        }
    }

}
export default ws;